package com.dingup.provider.controller.password;


import com.dingup.api.Util.*;
import com.dingup.api.base.HttpResContent;

import com.dingup.provider.controller.student.StudentController;
import com.dingup.provider.service.sys.SysUserService;
import com.dingup.util.GYunPianSmsUtil;
import com.suyeer.basic.util.BHttpResUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;
import static com.dingup.util.GConstUtil.SMS_VERIFY_CODE_MIN_DURATION;

/**
 * Created by wancheng on 2018/8/23.
 */
@Controller
@RequestMapping("/password")
public class PasswordController {

    private static Logger logger = LoggerFactory.getLogger(PasswordController.class);

    @Autowired
    SysUserService sysUserService;

    /**
     * 生成图片验证码
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/create_img_code", method = RequestMethod.GET)
    public void createImgCode(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("imageCodeId") String imageCodeId) {
        try {
            GCheckCodeUtil.setImageParameters(160, 50, -35, 12, 1.7f, 2f);
            GCheckCodeUtil.generateRandomCode(request, response, imageCodeId);
            logger.info("生成图形验证码 imageCodeId = {}", imageCodeId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证图片验证码
     *
     * @param imgCode
     * @param request
     * @param response
     */
    @RequestMapping(value = "/check_img_code.do", method = RequestMethod.POST)
    public void checkImgCode(String imgCode,
                             String imageCodeId,
                             HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("校验图片验证码");
        try {
            if (!ImageVerifyCodeUtil.getInstance().checkCode(imageCodeId, imgCode)) {
                throw new Exception("验证码错误");
            }
            logger.info("校验图片验证码 userMobilePhone = {} imgCode = {}", imageCodeId, imgCode);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    /**
     * 手机端注册-发送短信验证码
     *
     * @param userMobilePhone
     * @param request
     * @param response
     */
    @RequestMapping(value = "/send_verify_code.do", method = RequestMethod.POST)
    public void sendVerifyCode(String imgCode,
                               String userMobilePhone,
                               String imageCodeId,
                               HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Integer> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("发送短信验证码");
        try {
            // check.
            if (!ImageVerifyCodeUtil.getInstance().checkCode(imageCodeId, imgCode)) {
                throw new Exception("图片验证码错误");
            }
            //校验是否还能发送验证码
            if (VerifyCodeUtil.getInstance().ifCouldSendCode(userMobilePhone)) {
                //生成4位随机验证码
                String code = (int) (Math.random() * 9000) + 1000 + "";
                //发送短信验证码
                if (!GYunPianSmsUtil.SendVerifyCode(userMobilePhone, code)) {
                    throw new Exception("发送验证码失败");
                }
                VerifyCodeUtil.getInstance().putCode(userMobilePhone, code);
                logger.info("发送短信验证码 userMobilePhone = {} code = {}", userMobilePhone, code);
            }else{
                throw new Exception("验证未过期或超过次数限制");
            }
            saveSuccessMsgAndData(hrc, SMS_VERIFY_CODE_MIN_DURATION);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    /**
     * 检查手机验证码是否正确
     *
     * @param userMobilePhone
     * @param code
     * @param request
     * @param response
     */
    @RequestMapping(value = "/check_verify_code.do", method = RequestMethod.POST)
    public void checkVerifyCode(String userMobilePhone,
                                String code,
                                HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("检验短信验证码");
        try {

            // 从缓存中取出验证码
            Boolean ret = VerifyCodeUtil.getInstance().checkCode(userMobilePhone, code);
            logger.info("检验短信验证码 userMobilePhone = {} code = {}", userMobilePhone, code);
            // response.
            saveSuccessMsgAndData(hrc, ret);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_user_password.do", method = RequestMethod.POST)
    public void updatePassword(String userMobilePhone,
                               String password,
                               String code,
                               HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("修改密码");
        try {
            // 从缓存中取出验证码
            Boolean ret = VerifyCodeUtil.getInstance().checkCode(userMobilePhone, code);
            if (ret) {
                sysUserService.updatePassword(userMobilePhone, password);
            } else {
                throw new Exception("短信验证码错误或已失效");
            }
            logger.info("修改密码 userMobilePhone = {} password = {}", userMobilePhone, password);
            // response.
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
}
